package com.xiaoKe.zhonghzu.global.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.xiaoKe.zhonghzu.global.tool.SPUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

public class DownloadManager {
    private static final String TAG = "DownloadManager";
    private static final int BUFFER_SIZE = 8192; // 8KB缓冲区
    private final OkHttpClient client;
    private final Handler mainHandler;
    private Call currentCall;
    private DownloadListener listener;
    long  totalBytesRead;
    public DownloadManager() {
        mainHandler = new Handler(Looper.getMainLooper());

        // 配置OkHttpClient，添加进度拦截器
        client = new OkHttpClient.Builder()
                .addInterceptor(new ProgressInterceptor())
                .build();
    }

    // 设置下载监听器
    public void setListener(DownloadListener listener) {
        this.listener = listener;
    }

    // 开始下载（移除断点续传）
    public void startDownload(String url, String savePath) {
        // 取消旧下载任务
        cancelDownload();

        // 创建文件对象
        File file = new File(savePath);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            if (!parentDir.mkdirs()) {
                notifyListener(new DownloadState.Failed("创建目录失败"));
                return;
            }
        }
// POST 请求示例（需添加请求体）
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                "请求参数JSON字符串"
        );
        Request request = new Request.Builder()
                .header("Authorization", "Bearer " + SPUtils.getString("token", ""))
                .url(url)
                .post(requestBody) // 显式指定 POST 方法
                .build();

        currentCall = client.newCall(request);
        currentCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "下载失败: " + e.getMessage());
                notifyListener(new DownloadState.Failed(e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    notifyListener(new DownloadState.Failed("HTTP错误: " + response.code()));
                    return;
                }

                ResponseBody body = response.body();
                if (body == null) {
                    notifyListener(new DownloadState.Failed("响应体为空"));
                    return;
                }

                long contentLength = body.contentLength();
                long totalSize = contentLength == -1 ? 0 : contentLength; // 处理未知大小为0

                try (InputStream inputStream = body.byteStream();
                     FileOutputStream outputStream = new FileOutputStream(file)) { // 覆盖写入，移除断点续传

                    byte[] buffer = new byte[BUFFER_SIZE];
                    int bytesRead;
                    totalBytesRead = 0;

                    notifyListener(new DownloadState.Started(totalSize));

                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;

                        // 计算进度（0%-100%）
                        final int progress = (int) (totalSize > 0 ? (totalBytesRead * 100 / totalSize) : 0);
                        mainHandler.post(() -> {
                            if (listener != null) {
                                listener.onProgress(totalBytesRead, totalSize);
                            }
                        });
                    }

                    // 确保进度显示100%（处理totalSize为0的特殊情况）
                    if (totalSize == 0) {
                        mainHandler.post(() -> listener.onProgress(totalBytesRead, totalBytesRead));
                    }

                    notifyListener(new DownloadState.Success(file));

                } catch (IOException e) {
                    Log.e(TAG, "文件写入失败: " + e.getMessage());
                    if (file.exists() && !file.delete()) {
                        Log.e(TAG, "删除残留文件失败");
                    }
                    notifyListener(new DownloadState.Failed(e.getMessage()));
                }
            }
        });
    }

    // 取消下载
    public void cancelDownload() {
        if (currentCall != null && !currentCall.isCanceled()) {
            currentCall.cancel();
            notifyListener(new DownloadState.Canceled());
        }
    }

    // 通知监听器（在主线程执行）
    private void notifyListener(DownloadState state) {
        mainHandler.post(() -> {
            if (listener != null) {
                if (state instanceof DownloadState.Started) {
                    listener.onStart(((DownloadState.Started) state).getTotalSize());
                } else if (state instanceof DownloadState.Progress) {
                    DownloadState.Progress progressState = (DownloadState.Progress) state;
                    listener.onProgress(progressState.getCurrentBytes(), progressState.getTotalSize());
                } else if (state instanceof DownloadState.Success) {
                    listener.onSuccess(((DownloadState.Success) state).getFile());
                } else if (state instanceof DownloadState.Failed) {
                    listener.onFailed(((DownloadState.Failed) state).getErrorMessage());
                } else if (state instanceof DownloadState.Canceled) {
                    listener.onCanceled();
                }
            }
        });
    }

    // 进度拦截器（可选，用于监听网络传输进度）
    private class ProgressInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body()))
                    .build();
        }
    }

    // 带进度的响应体（可选）
    private class ProgressResponseBody extends ResponseBody {
        private final ResponseBody responseBody;
        private BufferedSource bufferedSource;

        public ProgressResponseBody(ResponseBody responseBody) {
            this.responseBody = responseBody;
        }

        @Override
        public okhttp3.MediaType contentType() {
            return responseBody.contentType();
        }

        @Override
        public long contentLength() {
            return responseBody.contentLength();
        }

        @Override
        public BufferedSource source() {
            if (bufferedSource == null) {
                bufferedSource = Okio.buffer(source(responseBody.source()));
            }
            return bufferedSource;
        }

        private Source source(Source source) {
            return new ForwardingSource(source) {
                long totalBytesRead = 0L;

                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    long bytesRead = super.read(sink, byteCount);
                    totalBytesRead += bytesRead != -1 ? bytesRead : 0;

                    // 打印网络层进度（可选）
                    if (responseBody.contentLength() > 0) {
                        int progress = (int) (totalBytesRead * 100 / responseBody.contentLength());
                        Log.d(TAG, "网络进度: " + progress + "%");
                    }

                    return bytesRead;
                }
            };
        }
    }

    // 下载状态接口（简化实现）
    public interface DownloadState {
        class Started implements DownloadState {
            private final long totalSize;
            public Started(long totalSize) { this.totalSize = totalSize; }
            public long getTotalSize() { return totalSize; }
        }

        class Progress implements DownloadState {
            private final long currentBytes;
            private final long totalSize;
            public Progress(long currentBytes, long totalSize) {
                this.currentBytes = currentBytes;
                this.totalSize = totalSize;
            }
            public long getCurrentBytes() { return currentBytes; }
            public long getTotalSize() { return totalSize; }
        }

        class Success implements DownloadState {
            private final File file;
            public Success(File file) { this.file = file; }
            public File getFile() { return file; }
        }

        class Failed implements DownloadState {
            private final String errorMessage;
            public Failed(String errorMessage) { this.errorMessage = errorMessage; }
            public String getErrorMessage() { return errorMessage; }
        }

        class Canceled implements DownloadState {}
    }

    // 下载监听器接口
    public interface DownloadListener {
        void onStart(long totalSize);
        void onProgress(long currentBytes, long totalSize);
        void onSuccess(File file);
        void onFailed(String errorMessage);
        void onCanceled();
    }
}